import nodemailer from 'nodemailer';
import { config } from 'dotenv';

config();

const nodemailerConfig = {
	host: process.env.EMAIL_HOST,
	port: parseInt(process.env.EMAIL_PORT, 10),
	// secure: true,
	// secureConnection: true,
	auth: {
		user: process.env.EMAIL_USER,
		pass: process.env.EMAIL_PASSWORD
	}
};

const transporter = nodemailer.createTransport(nodemailerConfig);

export function sendEmail(opt = {}) {
	const { subject = '', text = '' } = opt;

	if (!subject) {
		console.log('subject is required');

		return;
	}

	const mailConfig = {
		from: `Next AI <${process.env.EMAIL_USER}>`, // '昵称<发件人邮箱>'
		subject,
		to: process.env.EMAIL_TO,
		text
	};

	transporter.sendMail(mailConfig, (err, info) => {
		if (err) {
			console.error('error ', err);
			return;
		}

		console.log('mail sent:', info?.response);
		transporter.close();
	});
}
